import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { TextInput, StyleSheet, View, Text, ActivityIndicator } from 'react-native';
import { Button, FormLabel, FormInput, FormValidationMessage, Icon } from 'react-native-elements'
import { toast, executor, primaryColor, processSuccessLogin } from './utils';
import { getDeviceInfo, getLoginToken } from './clientStorage';
import { NavigationActions } from 'react-navigation';
import Loader from './widgets/Loader';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: 'white'
  },
  buttonContainer: {
    paddingVertical: 16
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingBottom: 16
  },
  fill: {
    flex: 1
  },
  button: {
    color: 'gray',
    textAlign: 'center'
  },
  heighLight: {
    color: primaryColor
  }
});

function getWorkerHomePage(worker) {
  return worker.factoryId?(worker.isChecker?'CheckerMain':'FactoryMain'):(worker.isCleaner?'CleanerMain':'Main');
}

class PasswordLoginPage extends Component {
  static navigationOptions = ({screenProps}) => {
    return {
      title: screenProps.chinese?'登录':'Sign In'
    };
  }
  state = { processing: false, username: '', password: ''}
  componentDidMount() {
    if (this.props.worker) {
      this.loginCheck(this.props.worker);
    }
  }
  componentWillReceiveProps(nextProps) {
    if (!this.props.worker&&nextProps.worker) {
      this.loginCheck(nextProps.worker);
    }
  }
  loginCheck = (worker) => {
    getLoginToken()
      .then(token => {
        if (token) {
          this.props.navigation.dispatch(NavigationActions.reset({
            index: 0,
            actions: [
              NavigationActions.navigate({routeName: getWorkerHomePage(worker)})
            ]
          }));
        }
      })
  }
  onUserNameChange = (username) => this.setState({username})
  onPasswordChange = (password) => this.setState({password})
  onCloseModel = () => this.setState({dialogShow: false})
  onUsernameDone = () => this.refs.password.focus()
  onForgotPassword = () => this.props.navigation.navigate('MobileLogin', {cca2: 'SG', countryCode: '65'})
  onSubmit = () => {
    const { username, password } = this.state;
    if (!username) return toast(this.props.screenProps.chinese?'用户名不可为空':'User name can not be empty');
    if (!password) return toast(this.props.screenProps.chinese?'密码不可为空':'Password can not be empty');

    executor(this.props.login, {username, password})
      .then(({res}) => {
        if (res&&res.login.token) {
          processSuccessLogin(res.login, this.props.screenProps, this.props.navigation, getWorkerHomePage(res.login));
        }
        this.setState({processing: false});
      });
    this.setState({processing: true});
  }
  render() {
    if (this.props.loading) return <Loader/>;
    const { chinese } = this.props.screenProps;

    return (
      <View style={styles.container}>
        <View style={styles.row}>
          <Icon name='email' color='gray'/>
          <View style={styles.fill}>
            <FormInput autoFocus onChangeText={this.onUserNameChange} onSubmitEditing={this.onUsernameDone}
              placeholder={chinese?'电子邮件 / 电话':'Email / Contact'} keyboardType="email-address" returnKeyType='next'/>
          </View>
        </View>
        <View style={styles.row}>
          <Icon name='lock' color='gray'/>
          <View style={styles.fill}>
            <FormInput ref='password' textInputRef='password' placeholder={chinese?'密码':'Password'}
              onChangeText={this.onPasswordChange} returnKeyType='done' onSubmitEditing={this.onSubmit}
              secureTextEntry/>
          </View>
        </View>
        <View style={styles.buttonContainer}>
          <Button backgroundColor={primaryColor} disabled={this.state.processing}
            icon={{name: 'sign-in', type: 'font-awesome'}} title={chinese?'登录':'Sign In'} onPress={this.onSubmit}/>
        </View>
        {this.state.processing&&<ActivityIndicator/>}
      </View>
    );
  }
}

export default compose(
  graphql(gql`
    query LoginPage {
      worker {
        id
        factoryId
        isCleaner
        isChecker
      }
    }
  `, {
    props: ({ownProps:{navigation}, data:{loading, worker}}) => {
      return {
        worker,
        loading
      };
    }
  }),
  graphql(gql`
    mutation PasswordLogin($username:String!,$password:String!,$device:UserDeviceInput) {
      login(username:$username,password:$password,device:$device,loginType:"worker") {
        id
        token
        factoryId
        isCleaner
        isChecker
      }
    }
  `, {
    props: ({ownProps, mutate}) => {
      return {
        login: (variables) =>
          getDeviceInfo()
            .then(device => mutate({
              variables: {
                ...variables,
                device
              }
            }))
      };
    }
  })
)(PasswordLoginPage);

